package com.seawater.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class HmacSHAUtil {

    public static String hmacSHA256(String message, String appSecretKey) {
        String signature = null;
        try {
            Mac hasher = Mac.getInstance("HmacSHA256");
            hasher.init(new SecretKeySpec(appSecretKey.getBytes(), "HmacSHA256"));

            byte[] hash = hasher.doFinal(message.getBytes());

            // 获得十六进制形式的签名
            signature = DatatypeConverter.printHexBinary(hash).toLowerCase();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            log.error(e.getMessage(), e);
        }

        return signature;
    }

    public static String sign(String appId,String appSecret,String body){
        if(StringUtils.isBlank(body)){
            return hmacSHA256("GET" + "\n" + appId + "\n" + appSecret,appSecret);
        }else {
            return hmacSHA256("POST" + "\n" + body + "\n" + appId + "\n" + appSecret,appSecret);
        }
    }

    public static void main(String[] args) {
        String appId = "294935713932001280";
        String appSecretKey = "1E4579B37B98417E8FA0701991D4EB20";

        String body = "{\r\n" +
                "\t\"id_number\":\"410825198305204017\",\r\n" +
                "\t\"name\":\"李小苛\",\r\n" +
                "\t\"mobile\":\"17703912356\",\r\n" +
                "\t\"report_id\":\"ER2019042522412939666666\"\r\n" +
                "}";
        String message1 = "POST" + "\n" + body + "\n" + appId + "\n" + appSecretKey;

        String message2 = "GET" + "\n" + appId + "\n" + appSecretKey;

        System.out.println("POST ---> "+HmacSHAUtil.hmacSHA256(message1, appSecretKey));
        System.out.println("GET ---> "+HmacSHAUtil.hmacSHA256(message2, appSecretKey));
    }
}
